<?php
declare (strict_types=1);

namespace app\user\model\user\admin;

use app\common\logic\Attach;
use app\common\model\BaseModel;
use app\common\model\DeviceType;
use app\school\model\school\admin\School;
use app\user\event\subscribes\user\admin\Account as UserSubscribe;
use app\user\model\user\Balance;
use app\user\model\user\Credit;
use app\user\model\user\Income;
use think\facade\Event;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

// use app\user\model\user\expenditure;

/**
 * 定义用户数据模型
 */
class Account extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'user';

    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';
    protected $append = [];

    /**
     * 设置隐藏字段
     *
     * @var array
     */
    protected $hidden = ['password', 'salt', 'register_device_text'];

    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'id'              => 'integer',
        'status'          => 'integer',
        'last_login_time' => 'timestamp',
    ];

    // 定义全局的查询范围
    protected $globalScope = ['mhm'];

    /**
     * 定义表主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 限制机构条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     * @param    [type]                         $query [description]
     * @return void [type]                                [description]
     */
    public function scopeMhm($query)
    {
        // 如果不是平台时, 加入机构条件限制
        if (!request()->is_platform) {
            $query->where('mhm_id', request()->mhm_id);
        }
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     *
     * @return   string
     */
    public static function onBeforeInsert($user)
    {
        // 自动填充注册IP
        $user->register_ip     = request()->ip();
        $user->register_device = 'admin';
        // 填充用户名
        $user->user_name = $user->phone;
        $user->nick_name = '用户' . $user->phone;
        $user->mhm_id    = $user->getAttr('mhm_id') ?: request()->mhm_id;
        $user->status    = 1;
    }

    /**
     * 来源
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-28
     *
     * @param string $value
     * @param        $data
     * @return mixed|string [type]                         [description]
     */
    public function getRegisterDeviceTextAttr($value = '', $data)
    {
        $text          = DeviceType::getDeviceList();
        $text['admin'] = '后台添加';

        return $text[$data['register_device']] ?? '后台添加';
    }

    /**
     * 成功创建之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-17
     */
    public static function onAfterInsert($user)
    {
        if (!Event::hasListener('UserCreated')) {
            Event::subscribe(UserSubscribe::class);
        }
        Event::trigger('UserCreated', $user);
    }

    /**
     * 成功修改之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-17
     */
    public static function onAfterUpdate($user)
    {
        if (!Event::hasListener('UserUpdated')) {
            Event::subscribe(UserSubscribe::class);
        }
        Event::trigger('UserUpdated', $user);
    }

    /**
     * 成功删除之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-17
     */
    public static function onAfterDelete($user)
    {
        if (!Event::hasListener('UserDeleted')) {
            Event::subscribe(UserSubscribe::class);
        }
        Event::trigger('UserDeleted', $user);
    }

    /**
     *  获取用户状态显示文字
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     *
     * @param string $value
     * @param        $data
     * @return string
     */
    public function getStatusTextAttr($value = '', $data): string
    {
        return $data['status'] == 1 ? '正常' : '禁用';
    }

    /**
     * 注册来源
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-06
     *
     * @param string $value [description]
     * @return string [type]                                [description]
     */
    public function getRegisterDeviceAttr($value = '')
    {
        return $value ?: 'Unknown';
    }

    /**
     * 设置密码密钥
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     */
    protected function setSaltAttr($value = '', $data): string
    {
        return 'pwd_' . mt_rand(100000, 999999);
    }

    /**
     * 加密密码
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     */
    public function setPasswordAttr($value = '', $data): string
    {
        // 触发设置密码密钥的方法
        $this->setAttr('salt', '');

        return $this->makePassword($value, $this->salt);
    }

    /**
     * 密码转为小写
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-14
     *
     * @param    [type]                         $value [description]
     * @return string [type]                                [description]
     */
    public function getPasswordAttr($value): string
    {
        return strtolower($value);
    }

    /**
     * 密码处理
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     *
     * @param $password
     * @param $salt
     * @return string [type]                                   [description]
     */
    public function makePassword($password, $salt): string
    {
        return md5(md5(strtolower($password)) . md5($salt));
    }

    /**
     * 设置状态查询条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     *
     * @param    [type]                         $query  [description]
     * @param integer $status 查询条件值
     */
    public function scopeStatus($query, $status = 1)
    {
        $query->where('status', $status);
    }

    /**
     * 头像地址
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-06
     *
     * @return BelongsTo [type]                         [description]
     */
    public function avatarUrl()
    {
        return $this->belongsTo(Attach::class, 'avatar')->bind(['avatar_url' => 'fileurl']);
    }

    // 余额
    public function balance()
    {
        return $this->hasOne(Balance::class, 'user_id')->bind(['balance']);
    }

    // 收入
    public function income()
    {
        return $this->hasOne(Income::class, 'user_id')->bind(['income']);
    }

    // 积分
    public function credit()
    {
        return $this->hasOne(Credit::class, 'user_id')->bind(['credit']);
    }

    // 消费额
    // public function expenditure()
    // {
    //     return $this->hasOne(Expenditure::class, 'user_id')->bind(['num']);
    // }

    /**
     * 机构信息
     *
     * @return BelongsTo
     */
    public function school()
    {
        return $this
            ->belongsTo(School::class, 'mhm_id')
            ->removeOption('soft_delete')
            ->bind([
                'school_name' => 'title'
            ]);
    }

}
